<template>
	<view class="search-page">
		<JNavBar show-back title="搜索"></JNavBar>
		<!-- 搜索头部 -->
		<view class="search-header">
			<view class="search-input-container">
				<JSearch v-model="searchKeyword" placeholder="请输入商品名称" :showAction="true" actionText="搜索" @search="handleSearch" @searchClick="handleSearchClick" />
			</view>
		</view>

		<!-- 搜索内容区域 -->
		<view class="search-content">
			<!-- 搜索历史 -->
			<view v-if="!hasSearched && searchHistory.length > 0" class="search-history">
				<view class="history-header">
					<text class="history-title">搜索历史</text>
					<text class="clear-history" @click="clearHistory">清空</text>
				</view>
				<view class="history-tags">
					<text v-for="(item, index) in searchHistory" :key="index" class="history-tag" @click="searchFromHistory(item)">
						{{ item }}
					</text>
				</view>
			</view>

			<!-- 热门搜索 -->
			<view v-if="!hasSearched" class="hot-search">
				<view class="hot-header">
					<text class="hot-title">热门搜索</text>
				</view>
				<view class="hot-tags">
					<text v-for="(item, index) in hotSearchList" :key="index" class="hot-tag" :class="{ 'hot-tag-top': index < 3 }" @click="searchFromHot(item)">
						{{ item }}
					</text>
				</view>
			</view>

			<!-- 筛选条件 -->
			<view v-if="hasSearched" class="search-filters">
				<JGoodsFilter @filterChange="handleFilterChange" />
			</view>

			<!-- 搜索结果 -->
			<view v-if="hasSearched" class="search-results">
				<view class="results-header">
					<text class="results-count">找到 {{ searchResults.length }} 个商品</text>
					<view class="sort-options">
						<text
							v-for="(option, index) in sortOptions"
							:key="index"
							class="sort-option"
							:class="{ 'sort-option-active': currentSort === option.value }"
							@click="handleSort(option.value)"
						>
							{{ option.label }}
						</text>
					</view>
				</view>

				<!-- 商品列表 -->
				<JGoodsArr :goodsList="searchResults" @goodsClick="handleGoodsClick" @addToCartSuccess="handleAddToCartSuccess" @addToCartError="handleAddToCartError" />
			</view>

			<!-- 无搜索结果 -->
			<view v-if="hasSearched && searchResults.length === 0" class="no-results">
				<view class="no-results-icon">🔍</view>
				<text class="no-results-text">没有找到相关商品</text>
				<text class="no-results-tip">试试其他关键词吧</text>
			</view>
		</view>
	</view>
</template>

<script>
import { waterfallGoodsList } from '@/components/JGoodsArr/example-data.js';

export default {
	name: 'SearchPage',
	data() {
		return {
			// 搜索关键词
			searchKeyword: '',
			// 是否已搜索
			hasSearched: false,
			// 搜索结果
			searchResults: [],
			// 搜索历史
			searchHistory: [],
			// 热门搜索
			hotSearchList: ['新鲜蔬菜', '有机水果', '优质肉类', '海鲜水产', '进口食品', '有机牛奶', '绿色蔬菜', '新鲜水果'],
			// 排序选项
			sortOptions: [
				{ label: '综合', value: 'default' },
				{ label: '价格', value: 'price' },
				{ label: '销量', value: 'sales' },
				{ label: '新品', value: 'new' }
			],
			// 当前排序
			currentSort: 'default',
			// 筛选条件
			filterConditions: {}
		};
	},
	onLoad() {
		this.loadSearchHistory();
	},
	methods: {
		/**
		 * 处理搜索
		 */
		handleSearch(keyword) {
			if (!keyword || !keyword.trim()) {
				uni.showToast({
					title: '请输入搜索关键词',
					icon: 'none'
				});
				return;
			}

			this.searchKeyword = keyword.trim();
			this.performSearch();
		},

		/**
		 * 处理搜索框点击
		 */
		handleSearchClick() {
			// 搜索框点击时聚焦输入框
			console.log('搜索框被点击');
			// 这里可以添加聚焦输入框的逻辑
			// 由于uni-app的限制，我们通过其他方式处理
		},

		/**
		 * 执行搜索
		 */
		performSearch() {
			// 添加到搜索历史
			this.addToHistory(this.searchKeyword);

			// 模拟搜索
			this.hasSearched = true;
			this.searchResults = this.filterGoods(waterfallGoodsList, this.searchKeyword);

			// 显示搜索结果提示
			uni.showToast({
				title: `找到 ${this.searchResults.length} 个商品`,
				icon: 'none'
			});
		},

		/**
		 * 从历史记录搜索
		 */
		searchFromHistory(keyword) {
			this.searchKeyword = keyword;
			this.performSearch();
		},

		/**
		 * 从热门搜索
		 */
		searchFromHot(keyword) {
			this.searchKeyword = keyword;
			this.performSearch();
		},

		/**
		 * 过滤商品
		 */
		filterGoods(goodsList, keyword) {
			return goodsList.filter((item) => {
				return item.name.toLowerCase().includes(keyword.toLowerCase()) || (item.id && item.id.toString().includes(keyword));
			});
		},

		/**
		 * 处理筛选条件变化
		 */
		handleFilterChange(conditions) {
			this.filterConditions = conditions;
			this.applyFilters();
		},

		/**
		 * 应用筛选条件
		 */
		applyFilters() {
			let results = [...waterfallGoodsList];

			// 关键词筛选
			if (this.searchKeyword) {
				results = this.filterGoods(results, this.searchKeyword);
			}

			// 其他筛选条件
			if (this.filterConditions.priceRange) {
				// 价格筛选逻辑
			}

			this.searchResults = results;
		},

		/**
		 * 处理排序
		 */
		handleSort(sortType) {
			this.currentSort = sortType;
			this.sortResults();
		},

		/**
		 * 排序结果
		 */
		sortResults() {
			switch (this.currentSort) {
				case 'price':
					this.searchResults.sort((a, b) => a.price - b.price);
					break;
				case 'sales':
					this.searchResults.sort((a, b) => (b.sales || 0) - (a.sales || 0));
					break;
				case 'new':
					this.searchResults.sort((a, b) => b.id - a.id);
					break;
				default:
					// 综合排序保持原顺序
					break;
			}
		},

		/**
		 * 处理商品点击
		 */
		handleGoodsClick(item) {
			console.log('点击商品:', item);
			uni.navigateTo({
				url: `/pages/goods/goods?id=${item.id}`
			});
		},

		/**
		 * 处理添加到购物车成功
		 */
		handleAddToCartSuccess(item) {
			uni.showToast({
				title: '已添加到购物车',
				icon: 'success'
			});
		},

		/**
		 * 处理添加到购物车失败
		 */
		handleAddToCartError(error) {
			uni.showToast({
				title: '添加失败，请重试',
				icon: 'none'
			});
		},

		/**
		 * 添加到搜索历史
		 */
		addToHistory(keyword) {
			// 移除重复项
			this.searchHistory = this.searchHistory.filter((item) => item !== keyword);
			// 添加到开头
			this.searchHistory.unshift(keyword);
			// 限制历史记录数量
			if (this.searchHistory.length > 10) {
				this.searchHistory = this.searchHistory.slice(0, 10);
			}
			// 保存到本地存储
			uni.setStorageSync('searchHistory', this.searchHistory);
		},

		/**
		 * 加载搜索历史
		 */
		loadSearchHistory() {
			const history = uni.getStorageSync('searchHistory');
			if (history && Array.isArray(history)) {
				this.searchHistory = history;
			}
		},

		/**
		 * 清空搜索历史
		 */
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清空搜索历史吗？',
				success: (res) => {
					if (res.confirm) {
						this.searchHistory = [];
						uni.removeStorageSync('searchHistory');
					}
				}
			});
		}
	}
};
</script>

<style lang="less">
.search-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.search-header {
	background: #fff;
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
	.search-input-container {
		width: 100%;
	}
}

.search-content {
	padding: 20rpx;
}

/* 搜索历史 */
.search-history {
	margin-bottom: 40rpx;
}

.history-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.history-title {
	font-size: 28rpx;
	color: #333;
	font-weight: 600;
}

.clear-history {
	font-size: 24rpx;
	color: #999;
}

.history-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
}

.history-tag {
	background: #f0f0f0;
	color: #666;
	padding: 12rpx 24rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
}

/* 热门搜索 */
.hot-search {
	margin-bottom: 40rpx;
}

.hot-header {
	margin-bottom: 20rpx;
}

.hot-title {
	font-size: 28rpx;
	color: #333;
	font-weight: 600;
}

.hot-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
}

.hot-tag {
	background: #fff;
	color: #666;
	padding: 12rpx 24rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
	border: 1rpx solid #eee;

	&.hot-tag-top {
		background: #ff6b35;
		color: #fff;
		border-color: #ff6b35;
	}
}

/* 筛选条件 */
.search-filters {
	margin-bottom: 20rpx;
}

/* 搜索结果 */
.search-results {
	background: #f5f5f5;
}

.results-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: #fff;
	padding: 20rpx;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
}

.results-count {
	font-size: 28rpx;
	color: #333;
}

.sort-options {
	display: flex;
	gap: 20rpx;
}

.sort-option {
	font-size: 24rpx;
	color: #666;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;

	&.sort-option-active {
		background: #ff6b35;
		color: #fff;
	}
}

/* 无搜索结果 */
.no-results {
	text-align: center;
	padding: 100rpx 40rpx;
	background: #fff;
	border-radius: 12rpx;
}

.no-results-icon {
	font-size: 80rpx;
	margin-bottom: 20rpx;
}

.no-results-text {
	display: block;
	font-size: 32rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.no-results-tip {
	font-size: 24rpx;
	color: #999;
}
</style>
